# backend/crud/subscription.py
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from backend.models.subscription import Subscription
from backend.models.node import Node  # ✅ 单独导入
from backend.models.user_subscription import UserSubscription  # ✅ 单独导入
from backend.schemas.subscription import SubscriptionCreate

async def create_subscription(db: AsyncSession, data: SubscriptionCreate):
    # 将 schema 转为 ORM 模型
    sub = Subscription(**data.dict())
    db.add(sub)
    await db.commit()
    await db.refresh(sub)
    return sub

async def get_subscriptions(db: AsyncSession, skip: int = 0, limit: int = 100):
    result = await db.execute(select(Subscription).offset(skip).limit(limit))
    return result.scalars().all()

async def update_subscription(db: AsyncSession, sub_id: str, data):
    result = await db.execute(select(Subscription).where(Subscription.id == sub_id))
    sub = result.scalar_one_or_none()
    if not sub:
        return None
    for k, v in data.dict(exclude_unset=True).items():
        setattr(sub, k, v)
    await db.commit()
    await db.refresh(sub)
    return sub